import { cartList, apiCartDelete, apiCartAdjustNum, apiGetPayOrder } from '../../api/index'
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    disImg: true,
    userId: 0,
    scrollHeight: 0,
    scrollTop: 0,
    cartPrice: 0,
    list: [],
    hotGoods: [],
    userInfo: 0,
    cartnum: 0,
    type: 0,
    checkedAll: false,
    allNum: 0,
    allPrice: 0,
    makeMoney: 0,
    loads: true
  },
  // 购物车列表
  getCarList () {
    cartList().then(
      res => {
        console.log(res)
        this.setData({
          list: res.data.cart_list,
          checkedAll: false,
          allNum: 0,
          allPrice: 0,
          makeMoney: 0,
          loads: false
        })
        wx.stopPullDownRefresh()
      }
    )
  },
  // 选中
  isCheckBox (e) {
    let data = this.data.list
    let checkAll = false
    data[e.currentTarget.dataset.index].checked = !data[e.currentTarget.dataset.index].checked
    for (let i = 0; i < data.length; i++) {
      if (data[i].checked) {
        checkAll = true
      } else {
        checkAll = false
        break
      }
    }
    let obj = this.calcAll(data)
    this.setData({
      list: data,
      checkedAll: checkAll,
      ...obj
    })
  },
  calcAll (data) {
    let num = 0
    let price = 0
    let money = 0
    for (let i = 0; i < data.length; i++) {
      if (data[i].checked) {
        num++
        price += (data[i].price - 0) * data[i].num
        money += (data[i].make_money - 0) * data[i].num
      }
    }
    return {
      allNum: num,
      allPrice: price === 0 ? 0 : price.toFixed(2),
      makeMoney: money === 0 ? 0 : money.toFixed(2)
    }
  },
  // 全选
  checkAll () {
    let data = this.data.list
    for (let i = 0; i < data.length; i++) {
      if (this.data.checkedAll) {
        data[i].checked = false
      } else {
        data[i].checked = true
      }
    }
    let obj = this.calcAll(data)
    this.setData({
      list: data,
      checkedAll: !this.data.checkedAll,
      ...obj
    })
  },
  // 去逛逛
  toShop () {
    wx.switchTab({
      url: '../shopping/shopping'
    })
  },
  // 修改购物车数量
  changeNum (cartid, num) {
    apiCartAdjustNum({ cartid, num, loading: true }).then(
      res => {
        let obj = this.calcAll(this.data.list)
        this.setData({
          ...obj
        })
      }
    )
  },
  // 增加商品
  upNum (e) {
    console.log(e.target.dataset.data)
    let data = this.data.list
    let item = data[e.target.dataset.index]
    let obj = {}
    this.max_buy = e.target.dataset.data > 0 ? (e.target.dataset.data - 0) : item.stock
    if (item.num >= this.max_buy) {
      wx.showToast({
        title: '超出库存了',
        mask: true,
        icon: 'none'
      })
    } else {
      item.num++
      obj = this.calcAll(data)
      this.changeNum(item.cart_id, item.num)
      this.setData({
        list: data,
        allPrice: (obj.allPrice - 0) === 0 ? 0 : (obj.allPrice - 0).toFixed(2)
      })
    }
  },
  // 减少商品
  downNum (e) {
    let data = this.data.list
    let item = data[e.target.dataset.index]
    let obj = {}
    let minBuy = e.target.dataset.data > 0 ? e.target.dataset.data : 1
    if (item.num <= minBuy) {
      wx.showToast({
        title: `不能再少了`,
        mask: true,
        icon: 'none'
      })
    } else {
      item.num--
      obj = this.calcAll(data)
      this.changeNum(item.cart_id, item.num)
      this.setData({
        list: data,
        allPrice: obj.allPrice
      })
    }
  },
  // 跳转商品详情
  goDetail (e) {
    wx.navigateTo({
      url: `../goods-detail/goods-detail?id=${e.detail}`
    })
  },
  // 删除
  cancelCar (e) {
    wx.showModal({
      title: '提示',
      content: '您确定删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          apiCartDelete({ del_id: e.currentTarget.dataset.id }).then(
            r => {
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                success: () => {
                  this.getCarList()
                }
              })
            }
          )
        } else if (res.cancel) {
        }
      }
    })
  },
  // 结算
  allPrice () {
    let carList = this.data.list
    let cartIds = ''
    var allFalse = carList.every(item => !item.checked)
    if (allFalse) {
      wx.showToast({
        title: '请选择商品',
        mask: true,
        icon: 'none'
      })
      return
    }
    this.data.list.forEach(item => {
      if (item.checked) {
        cartIds += item.cart_id + ','
      }
    })
    cartIds = cartIds.slice(0, -1)
    apiGetPayOrder({
      order_tag: 'cart',
      cart_list: cartIds,
      order_sku_list: ''
    }).then(res => {
      console.log(res)
      let data = JSON.stringify(res.data.itemlist)
      let shipping = JSON.stringify(res.data.express_company_list)
      // 立即购买
      wx.navigateTo({
        url: `../shop-detail-order/shop-detail-order?data=${data}&shipping=${shipping}`
      })
    })
  },
  // 跳转商品详情
  toGoodDetail (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../goods-detail/goods-detail?id=${id}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad () {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.getCarList()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    // this.setData({
    //   list: []
    // })
    // this.getCarList()
  },
  // 页面滑动到底部
  bindDownLoad () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
  }
}
Page(page)
